local hunyi = fk.CreateSkill{
  name = "lingling__hunyi",
}

Fk:loadTranslationTable{
  ["lingling__hunyi"] = "混一",
  [":lingling__hunyi"] = "出牌阶段限一次，你可以获得所有其他角色所有手牌，然后其他角色依次获得你X张手牌（X为其此次失去的手牌数），"..
  "你可以令一名其他角色优先获得。",

  ["#lingling__hunyi"] = "混一：获得所有角色所有手牌，然后这些角色依次获得你等量的牌",
  ["#lingling__hunyi-choose"] = "混一：你可以令一名角色先获得你的手牌，然后其余角色依次获得",
  ["#lingling__hunyi-prey"] = "混一：获得 %src 的%arg张手牌",
}

hunyi:addEffect("active", {
  anim_type = "control",
  prompt = "#lingling__hunyi",
  card_num = 0,
  target_num = 0,
  card_filter = Util.FalseFunc,
  can_use = function(self, player)
    return player:usedSkillTimes(hunyi.name, Player.HistoryPhase) == 0 and
      table.find(Fk:currentRoom().alive_players, function (p)
        return p ~= player and not p:isKongcheng()
      end)
  end,
  on_use = function(self, room, effect)
    local player = effect.from
    room:doIndicate(player, room:getOtherPlayers(player, false))
    local mapper = {}
    for _, target in ipairs(room:getOtherPlayers(player)) do
      if not target:isKongcheng() then
        mapper[target] = target:getHandcardNum()
        room:moveCardTo(target:getCardIds("h"), Card.PlayerHand, player, fk.ReasonPrey, hunyi.name, nil, false, player)
      end
      if player.dead then return end
    end
    local targets = {}
    for _, p in ipairs(room:getOtherPlayers(player, false)) do
      if mapper[p] then
        table.insert(targets, p)
      end
    end
    if player:isKongcheng() or #targets == 0 then return end
    local to = room:askToChoosePlayers(player, {
      min_num = 1,
      max_num = 1,
      targets = targets,
      skill_name = hunyi.name,
      prompt = "#lingling__hunyi-choose",
      cancelable = true,
    })
    if #to > 0 then
      to = to[1]
      table.removeOne(targets, to)
      local cards = room:askToChooseCards(to, {
        target = player,
        min = mapper[to],
        max = mapper[to],
        flag = "h",
        skill_name = hunyi.name,
        prompt = "#lingling__hunyi-prey:"..player.id.."::"..mapper[to],
      })
      room:moveCardTo(cards, Card.PlayerHand, to, fk.ReasonPrey, hunyi.name, nil, false, to)
      if player:isKongcheng() or player.dead then return end
    end
    for _, target in ipairs(room:getOtherPlayers(player)) do
      if table.contains(targets, target) and not target.dead then
        local cards = room:askToChooseCards(target, {
          target = player,
          min = mapper[target],
          max = mapper[target],
          flag = "h",
          skill_name = hunyi.name,
          prompt = "#lingling__hunyi-prey:"..player.id.."::"..mapper[target],
        })
        room:moveCardTo(cards, Card.PlayerHand, target, fk.ReasonPrey, hunyi.name, nil, false, target)
      end
      if player:isKongcheng() or player.dead then return end
    end
  end,
})

return hunyi
